package com.learn.training.multithread.chapter6.minchapter8.demo2;

import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class AccessLimitControl {
    // 任意时刻仅允许最多2个线程获取许可,且时公平锁
    final Semaphore semaphore = new Semaphore(2, true); // 5个许可，公平锁

    public String access(String name) throws InterruptedException {
        // 如果超过了许可数量,其他线程将在此等待:
        System.out.println(Thread.currentThread().getName() + "  is waiting for access");
        String result = "default";
        if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {//尝试获取许可，最多等待1秒
            try {
                Thread.sleep(1000);
                result = Thread.currentThread().getName() + "  get access   " + "   " + UUID.randomUUID();
                System.out.println(result);
                return result;
            }finally {
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + "  release");
            }
        }
        return result;
    }
}
